from flask import Flask
from flask_login import LoginManager
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy import MetaData
from config import DevelopmentConfig
from exts import mail, ckeditor, csrf, cache

naming_convention = {
    "ix": 'ix_%(column_0_label)s',
    "uq": "uq_%(table_name)s_%(column_0_name)s",
    "ck": "ck_%(table_name)s_%(column_0_name)s",
    "fk": "fk_%(table_name)s_%(column_0_name)s_%(referred_table_name)s",
    "pk": "pk_%(table_name)s"
}

login_manager = LoginManager()
login_manager.login_view = 'users.login'
login_manager.login_message_category = '欢迎回来'
login_manager.session_protection = 'strong'

from apps.basic import basic_bp
from apps.users import users_bp
from apps.goods import goods_bp
from apps.orders import orders_bp
from apps.members import members_bp
from apps.cates import cates_bp


def create_app(**kwargs):
    app = Flask(__name__, static_folder='static', template_folder='templates')
    app.json.ensure_ascii = False
    app.config['JSON_AS_ASCII'] = False
    app.config.from_object(DevelopmentConfig)
    login_manager.init_app(app)
    app.register_blueprint(basic_bp, url_prefix='/basic')
    app.register_blueprint(users_bp, url_prefix='/users')
    app.register_blueprint(goods_bp, url_prefix='/goods')
    app.register_blueprint(orders_bp, url_prefix='/orders')
    app.register_blueprint(members_bp, url_prefix='/members')
    app.register_blueprint(cates_bp, url_prefix='/cates')
    db = SQLAlchemy(app, metadata=MetaData(naming_convention=naming_convention))
    db.init_app(app)
    init_celery(celery=kwargs.get('celery'), app=app)
    ckeditor.init_app(app)
    csrf.init_app(app)
    mail.init_app(app)
    cache.init_app(app)
    return app


def init_celery(celery, app):
    if celery is not None:
        class ContextTask(celery.Task):
            abstract = True

            def __call__(self, *args, **kwargs):
                with app.app_context():
                    return self.run(*args, **kwargs)

        celery.conf.task_cls = ContextTask
